<template>
	<!-- 上传图片和视频 -->
	<view class="container" @click.stop="selectFile" :style="{ height: conHeight + 'px' }">
		<view class="icon">
			<uni-icons
				:type="currentIcon"
				:size="iconSize"
			></uni-icons>
		</view>
		<view class="desc" v-if="descShow">
			{{ currentDesc }}
		</view>
	</view>
</template>

<script>
	import { baseUrl } from '@/common/config'
	export default {
		name:"uploadMedia",
		props: {
			iconType: {
				type: String,
				default: 'camera'	// 相机
			},
			iconSize: {
				type: String,
				default: '30'	// 大小
			},
			descShow: {
				type: Boolean,
				default: true,
			},
			desc: {
				type: String,
				default: '添加图片/视频'	// 描述文字
			},
			mediaType: {
				type: Array,
				default: () => ['image','video']
			},
			count: {
				type: Number,	// 最多可以选择的文件个数
				default:9
			},
			isCheckDuration: {	// 是否校验上传视频时长
				type: Boolean,
				default: true
			},
			minDuration : {
				type: Number,	// 拍摄视频最长拍摄时间，单位秒。时间范围为 3s 至 30s 之间
				default: 3
			},
			maxDuration : {
				type: Number,	// 拍摄视频最长拍摄时间，单位秒。时间范围为 3s 至 30s 之间
				default: 30
			},
			videoSize: {	// 文件大小 size 单位:mb
				type: Number,
				default: 200
			},
			conHeight: { // 容器高度 单位: px
				type: Number,
				default: 88
			},
			isCover: {	// 当上传视频时，是否需要自动生成封面缩略图
				type: Boolean,
				default: false
			}
		},
		mounted(){
			this.reset()
		},
		data() {
			return {
				flag: true,	// 是否能上传
				currentIcon: '', 
				currentDesc: '',
				uploading: 'spinner-cycle',	// 上传中的icon
				descing: '上传中...'
			};
		},
		methods: {
			// 初始化
			reset(){
				this.flag = true
				this.currentIcon = this.iconType
				this.currentDesc = this.desc
			},
			// 加载中
			ing(){
				this.flag = false
				this.currentIcon = this.uploading
				this.currentDesc = this.descing
			},
			uploadFileFun(tempFilePath){
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: `${baseUrl}/user-center/app-file/upload-file`,
						filePath: tempFilePath,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
							"Content-Type": "multipart/form-data",
						},
						success: (res) => {
							// console.log('upload', res);
							const result = JSON.parse(res.data)
							const url = result.datas
							resolve(url)
						},
						fail: (res) => {
							uni.showToast({
								title: '操作失败',
								icon: 'exception'
							})
							reject(res)
						}
					});
				})
			},
			selectFile() {
				if(!this.flag){
					uni.showToast({
						title: '上传中',
						icon: 'error'
					})
					return false
				}
				
				uni.chooseMedia({
				  count: this.count,
				  mediaType: this.mediaType,
				  sourceType: ['album', 'camera'],
				  maxDuration: this.maxDuration,
				  camera: 'back',
				  success: (res) => {
						console.log('media-----', res);				
						// 文件类型
						if (res.tempFiles.some(i => i.fileType === 'video')) {
							// 视频的大小
							const arr = res.tempFiles.find(i => i.size > (this.videoSize * 1024 * 1024) )
							if(arr){
								uni.showToast({
									title: `上传视频大小不能超过${this.videoSize}MB`,
									icon: 'none'
								})
								return
							}
						
						} else {
							// 其他情况
						}
						
						// 变更加载中状态
						this.ing()
						
						// console.log('res.tempFiles', res.tempFiles);
						res.tempFiles.forEach(async i => {
							
							// // 校验视频时长
							if(this.isCheckDuration){
								if (i.duration > this.maxDuration) {
									uni.showToast({
										title: `视频时长不能超过${this.maxDuration}秒`,
										icon: 'none'
									})
									this.reset()
									return false
								}
								if (i.duration < this.minDuration) {
									uni.showToast({
										title: `视频时长不能小于${this.minDuration}秒`,
										icon: 'none'
									})
									this.reset()
									return false
								}
							}
							
							if(this.isCover){
								const url = await this.uploadFileFun(i.thumbTempFilePath)
								this.$emit('coverUrl', url)
							}
							
							uni.uploadFile({
								url: `${baseUrl}/user-center/app-file/upload-file`,
								filePath: i.tempFilePath,
								name: 'file',
								formData: {
									user: 'test'
								},
								header: {
									'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
									"Content-Type": "multipart/form-data",
								},
								success: (res) => {						
									let result = JSON.parse(res.data)
									const fileName = result.datas.split('/').at(-1)
									// 只返回文件路径
									this.$emit('handleFile', result.datas)
									// 返回文件路径和名字
									this.$emit('handleFileInfo', { name: fileName, url: result.datas })
									
									// 上传的视频宽高
									this.$emit('widthHi', { width: i.width , height: i.height })
									
									this.reset()
								},
								fail: () => {
									uni.showToast({
										title: '操作失败',
										icon: 'exception'
									})
									
									this.reset()
								}
							});
						})

				  }
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.container {
	width: 100%;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: center;
	// height: 176rpx;
	padding: 30rpx 20rpx;
	background-color: #f5f5f6;
	border-radius: 20rpx;
	.icon {
		height: 100%;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.desc {
		font-size: 13px;
		color: #9e9e9e;
	}
}
</style>